<template>
    <v-menu
        ref="menu"
        v-model="menu"
        :close-on-content-click="false"
        :value="value"
        transition="scale-transition"
        offset-y
        max-width="290px"
        min-width="290px"
    >
    <template v-slot:activator="{ on, attrs }">
        <v-text-field
            v-model="computedDateFormatted"
            :label="label"
            prepend-inner-icon="mdi-calendar-range"
            readonly
            v-bind="attrs"
            v-on="on"
            outlined
            dense
            :rules="rules"
            :hide-details="hideDetails"
        ></v-text-field>
    </template>
    <v-date-picker
        ref="picker"
        v-model="date"
        :max="max"
        :min="min"
    >
        <v-spacer></v-spacer>
        <v-btn text color="primary" @click="menu = false">Cancel</v-btn>
        <v-btn text color="primary" @click="setDate">OK</v-btn>
    </v-date-picker>
    </v-menu>
</template>
<script lang="ts">
import Vue from 'vue';
import moment from 'moment';

export default Vue.extend({
    props: {
        label: {
            type: String,
            default: 'Date',
        },
        value: {
            type: String,
            default: '',
        },
        rules: {
        },
        max: {
            type: String,
            default: undefined,
        },
        min: {
            type: String,
            default: '1950-01-01',
        },
        hideDetails: {
            type: Boolean,
            default: false,
        },
    },
    data(): {
        menu: boolean;
        date: string;
        } {
        return {
            menu: false,
            date: this.value,
        };
    },
    computed: {
        computedDateFormatted(): string | null {
            return this.formatDate(this.date);
        },
    },
    watch: {
        date() {
            this.$emit('input', this.date);
        },
        value: {
            handler(val) {
                this.date = val;
            },
        },
    },
    methods: {
        setDate() {
            this.menu = false;
            this.$emit('input', this.date);
        },
        formatDate(date: string) {
            if (!date) return null;
            return moment(date).format('YYYY/MM/DD');
        },
    },
});
</script>
